package com.cn.xiaonuo.slbfinances.members.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cn.xiaonuo.common.constant.Status;
import com.cn.xiaonuo.common.entity.BusinessMessage;
import com.cn.xiaonuo.common.utils.ExportExcelUtils;
import com.cn.xiaonuo.common.vo.ExcelData;
import com.cn.xiaonuo.dbs.core.annotation.DataSource;
import com.cn.xiaonuo.slbfinances.members.param.SlUserParam;
import com.cn.xiaonuo.slbfinances.members.entity.SlIntegrateLog;
import com.cn.xiaonuo.slbfinances.members.entity.SlSystemLogs;
import com.cn.xiaonuo.slbfinances.members.entity.SlUser;
import com.cn.xiaonuo.slbfinances.members.entity.SlUserDjjLog;
import com.cn.xiaonuo.slbfinances.members.mapper.*;
import com.cn.xiaonuo.slbfinances.members.service.IMemberService;
import com.cn.xiaonuo.slbfinances.slbagents.entity.SlUserData;
import com.cn.xiaonuo.slbfinances.slbagents.entity.SlUserDetail;
import com.cn.xiaonuo.slbfinances.slbagents.entity.SlXsProxyData;
import com.cn.xiaonuo.slbfinances.slbagents.service.UserAgentService;
import com.cn.xiaonuo.slbfinances.slbagents.service.XsProxyDataService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class IMemberServiceImpl extends ServiceImpl<SlUserMapper, SlUser> implements IMemberService {
    @Resource
    private SlUserMapper slUserMapper;
    @Resource
    private SlIntegrateLogMapper slIntegrateLogMapper;
    @Resource
    private SlUserDjjLogMapper slUserDjjLogMapper;
    @Resource
    private SlSystemLogsMapper slSystemLogsMapper;
    @Resource
    private CmSystemMapper cmSystemMapper;
    @Resource
    private UserAgentService userAgentService;

    @DataSource(name = "jyb_soole_data_hn")
    @Override
    public BusinessMessage exchange(Integer type, Integer cuserId, Integer muserId, BigDecimal money, Integer operaUserId, String userName) {
        BusinessMessage message = new BusinessMessage();
        try {
            if (null == type) {
                message.setCode("-1");
                message.setMessage("请选择类型");
                message.setSuccess(false);
                return message;
            }
            if (null == cuserId) {
                message.setCode("-1");
                message.setMessage("转出方不能为空");
                message.setSuccess(false);
                return message;
            }
            if (null == muserId) {
                message.setCode("-1");
                message.setMessage("转入方不能为空");
                message.setSuccess(false);
                return message;
            }
            if (null == money) {
                message.setCode("-1");
                message.setMessage("转入数量不能为空");
                message.setSuccess(false);
                return message;
            }
            if (money.compareTo(BigDecimal.valueOf(0)) <= 0) {
                message.setCode("-1");
                message.setMessage("转入数量不正确,请重新输入");
                message.setSuccess(false);
                return message;
            }
            //用户积分转兑礼卷
            if (type.intValue() == 1) {
                //1.查询兑换用户积分
                SlUser slUser = slUserMapper.selectById(cuserId);
                if (null == slUser) {
                    message.setMessage("兑换用户不存在");
                    message.setSuccess(false);
                    message.setCode("-1");
                    return message;
                }
                //1.1判断转出方法积分够不够
                if (slUser.getIntegration().compareTo(money) < 0) {
                    message.setMessage("兑换用户积分不足");
                    message.setSuccess(false);
                    message.setCode("-1");
                    return message;
                }
                //1.2扣除转出方积分和添加兑礼卷
                slUser.setIntegration(slUser.getIntegration().subtract(money));
                slUser.setPrDjj(slUser.getPrDjj().add(money));
                slUser.setDjj(slUser.getDjj().add(money));
                slUser.setUpdatedAt(new Date());
                slUserMapper.updateById(slUser);
                //2.添加积分日志
                SlIntegrateLog slIntegrateLog = new SlIntegrateLog();
                slIntegrateLog.setType(1);
                slIntegrateLog.setContent("积分转兑礼券");
                slIntegrateLog.setOutId(cuserId);
                slIntegrateLog.setUserId(muserId);
                slIntegrateLog.setIntegrate(money);
                slIntegrateLog.setCreatedAt(new Date());
                slIntegrateLogMapper.insert(slIntegrateLog);
                //1.2添加兑礼卷日志
                SlUserDjjLog slUserDjjLog = new SlUserDjjLog();
                slUserDjjLog.setSourceId(-505);
                slUserDjjLog.setType(1);
                slUserDjjLog.setTotal(money);
                slUserDjjLog.setUserId(cuserId);
                slUserDjjLog.setStates(1);
                slUserDjjLog.setCreateTime(new Date());
                slUserDjjLog.setPastTime(LocalDate.now().plusDays(30).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 00:00:00");
                slUserDjjLogMapper.insert(slUserDjjLog);
                //4.添加日志
                SlSystemLogs slSystemLogs = new SlSystemLogs();
                slSystemLogs.setTitle("会员积分转兑礼券");
                slSystemLogs.setContent("会员ID" + cuserId + "转出" + money + "积分，会员ID" + muserId + "增加" + money + "兑礼券");
                slSystemLogs.setType(false);
                slSystemLogs.setCreatedAt(new Date());
                slSystemLogs.setUpdatedAt(new Date());
                slSystemLogs.setAction("");
                slSystemLogs.setUserid(operaUserId);
                slSystemLogs.setUsername(userName);
                int i = slSystemLogsMapper.insert(slSystemLogs);
                if (i == 1) {
                    message.setCode("200");
                    message.setSuccess(true);
                    message.setMessage("积分兑换兑礼卷成功");
                    return message;
                }

            }
            //两个账户之间兑礼卷转换
            if (type.intValue() == 2) {
                //1.查询转出方兑礼卷
                SlUser slUserOut = slUserMapper.selectById(cuserId);
                if (slUserOut.getDjj().compareTo(money) < 0) {
                    message.setMessage("转出方兑礼卷不足");
                    message.setSuccess(false);
                    message.setCode("-1");
                    return message;
                }
                //1.1扣除转出方兑礼卷
                slUserOut.setDjj(slUserOut.getDjj().subtract(money));
                slUserOut.setPrDjj(slUserOut.getPrDjj().subtract(money));
                slUserOut.setUpdatedAt(new Date());
                slUserMapper.updateById(slUserOut);
                //1.2添加兑礼卷减少日志
                SlUserDjjLog slUserDjjLog = new SlUserDjjLog();
                slUserDjjLog.setSourceId(-1001);
                slUserDjjLog.setType(1);
                slUserDjjLog.setTotal(money);
                slUserDjjLog.setUserId(cuserId);
                slUserDjjLogMapper.insert(slUserDjjLog);

                //2.查询转入方兑礼卷
                SlUser slUserIn = slUserMapper.selectById(muserId);
                //2.1添加兑礼卷
                slUserIn.setDjj(slUserIn.getDjj().add(money));
                slUserIn.setPrDjj(slUserIn.getPrDjj().add(money));
                slUserIn.setUpdatedAt(new Date());
                slUserMapper.updateById(slUserIn);
                //3.添加日志
                SlSystemLogs slSystemLogs = new SlSystemLogs();
                slSystemLogs.setTitle("会员兑礼券转账");
                slSystemLogs.setContent("会员ID" + cuserId + "转出" + money + "兑礼券至会员ID" + muserId);
                slSystemLogs.setType(false);
                slSystemLogs.setCreatedAt(new Date());
                slSystemLogs.setUpdatedAt(new Date());
                slSystemLogs.setAction("");
                slSystemLogs.setUserid(operaUserId);
                slSystemLogs.setUsername(userName);
                int i = slSystemLogsMapper.insert(slSystemLogs);
                if (i == 1) {
                    message.setCode("200");
                    message.setSuccess(true);
                    message.setMessage("会员兑礼卷转账成功");
                    return message;
                }
            }
        } catch (Exception e) {
            message.setSuccess(false);
            message.setMessage("操作失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return message;
    }

    @Override
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage queryRelation(Integer pageNum, Integer pageSize, String userId, String phone) {
        BusinessMessage message = new BusinessMessage();
        if (null == pageNum || pageNum <= 1) {
            pageNum = 1;
        }
        if (null == pageSize || pageSize <= 1) {
            pageSize = 10;
        }
        // 设置分页参数
        PageHelper.startPage(pageNum, pageSize);
        List<Map<String, Object>> maps = cmSystemMapper.queryRelation(userId, phone);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(maps);
        message.setSuccess(true);
        message.setMessage("查询数据成功");
        message.setData(pageInfo);
        return message;

    }

    @Override
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage queryLowerLevel(Integer pageNo, Integer pageSize, Integer userId) {
        BusinessMessage message = new BusinessMessage();
        if (null == pageNo || pageNo <= 1) {
            pageNo = 1;
        }
        if (null == pageSize || pageSize <= 1) {
            pageSize = 10;
        }
        // 设置分页参数
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String, Object>> maps = cmSystemMapper.queryLowerLevel(userId);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(maps);
        message.setSuccess(true);
        message.setMessage("查询数据成功");
        message.setData(pageInfo);
        return message;

    }

    @Override
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage membersPage(SlUserParam slUserParam) {
        BusinessMessage message = new BusinessMessage();
        try {
            Integer pageNo = slUserParam.getPageNo();
            Integer pageSize = slUserParam.getPageSize();
            if (null == pageNo || Integer.valueOf(pageNo) <= 1) {
                pageNo = 1;
            }
            if (null == pageSize || Integer.valueOf(pageSize) <= 1) {
                pageSize = 10;
            }
            // 设置分页参数
            PageHelper.startPage(pageNo, pageSize);
            List<Map<String, Object>> list = slUserMapper.selUserMebList(slUserParam);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);
            // 查询该店铺商品
            message.setData(pageInfo);
            message.setMessage(Status.success);
            message.setSuccess(true);
        } catch (Exception e) {
            message.setMessage(Status.fail);
            message.setCode(Status.failCode);
            message.setSuccess(false);
            e.printStackTrace();
        }
        return message;
    }


    @Override
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage membersDetail(SlUserParam slUserParam) {
        BusinessMessage message = new BusinessMessage();
        List<SlUserDetail> list = slUserMapper.membersDetail(slUserParam);
        SlUserDetail slUserDetail = new SlUserDetail();
        if (list != null) {
            slUserDetail = list.get(0);
            Integer userId = Convert.toInt(slUserDetail.getUserId());
            //获取上级id
            String superiorUserId = slUserDetail.getSuperiorUserId();
            slUserDetail.setSuperiorUserId(superiorUserId);
            //获取服务中心
            Map<String, Object> map = slUserMapper.getCenterByUserId(userId);
            if (map != null) {
                //获取服务中心
                slUserDetail.setServiceName(Convert.toStr(map.get("serviceName")));
            } else {
                slUserDetail.setServiceName("振兴乡村精品店");
            }
            if (superiorUserId != null) {
                SlUser slUser = slUserMapper.selectById(Convert.toInt(superiorUserId));
                if (slUser != null) {
                    slUserDetail.setSuperiorPhone(slUser.getPhone());
                    //获取代理身份
                    SlUserData superiorSlUserData = userAgentService.queryOne(userId);
                    slUserDetail.setSuperiorAgent(superiorSlUserData.getAgent());
                }
            }
            //获取代理身份
            SlUserData slUserData = userAgentService.queryOne(userId);
            slUserDetail.setAgent(slUserData.getAgent());

        }
        message.setSuccess(true);
        message.setMessage("查询数据成功");
        message.setCode("200");
        message.setData(slUserDetail);
        return message;
    }

    @Override
    @DataSource(name = "jyb_soole_data_hn")
    public void listExport(HttpServletResponse response, SlUserParam slUserParam) {
        List<Map<String, Object>> list = slUserMapper.selUserMebList(slUserParam);
        try {
            List<List<Object>> rows = new ArrayList();
            ExcelData data = new ExcelData();
            data.setName("会员列表导出");//sheet表名称
            //表头
            List<String> titles = new ArrayList();
            titles.add("搜了宝ID");
            titles.add("会员昵称");
            titles.add("真实姓名");
            titles.add("联系方式");
            titles.add("身份证号码");
            titles.add("银行卡号");
            titles.add("开户行");
            titles.add("开户支行");
            titles.add("银行预留手机号");
            titles.add("入住时间");
            data.setTitles(titles);
            for (Map map : list) {
                List<Object> row1 = new ArrayList();
                row1.add(map.get("userId"));
                row1.add(map.get("nickName"));
                row1.add(map.get("realName"));
                row1.add(map.get("phone"));
                row1.add(map.get("cardNumber"));
                row1.add(map.get("bankCardCode"));
                row1.add(map.get("bankName"));
                row1.add(map.get("openBranchBank"));
                row1.add(map.get("bankPhone"));
                row1.add(map.get("createdAt"));
                rows.add(row1);
            }
            data.setRows(rows);
            ExportExcelUtils.exportExcel(response, "会员列表导出.xlsx", data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
